﻿using Abp.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NRSoft.IdentityServer.SSOServer.Models;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using IdentityServer4.Services;
using Exceptionless;
using Exceptionless.Logging;

namespace NRSoft.IdentityServer.SSOServer.Controllers
{
    public class AccountController : AbpController
    {
        #region 构造函数
        private readonly IIdentityServerInteractionService _interactionService;

        /// <summary>
        /// 构造函数
        /// </summary>
        public AccountController(IIdentityServerInteractionService interactionService)
        {
            _interactionService = interactionService;
        }
        #endregion

        public IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> Login(string returnUrl = null)
        {
            //// Clear the existing external cookie to ensure a clean login process
            //await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                AuthenticationProperties props = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(1))
                };

                // issue authentication cookie with subject ID and username
                await HttpContext.SignInAsync("admin", model.Username, props);

                // 记录日志
                ExceptionlessClient.Default.CreateLog($"用户名（{model.Username}）成功登录SSO系统。", LogLevel.Info).AddTags("登录").Submit();

                return Redirect(returnUrl ?? "~/");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        /// <summary>
        /// 用户退出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //[ValidateAntiForgeryToken]
        public async Task<IActionResult> Logout([FromQuery]string logoutId, string returnUrl = "")
        {
            // 获取IdentityServer4登出上下文
            var logoutContext = await _interactionService.GetLogoutContextAsync(logoutId);

            // delete local authentication cookie
            await HttpContext.SignOutAsync();

            Logger.Info($"用户（{AbpSession.UserId}）退出系统。登出LogoutId为：{logoutId}");

            var vm = new LoggedOutViewModel()
            {
                SignOutIframeUrl = logoutContext.SignOutIFrameUrl,
                PostLogoutRedirectUri = logoutContext.PostLogoutRedirectUri ?? "/home/index"
            };
            return View(vm);

            //if (!string.IsNullOrWhiteSpace(logoutContext.PostLogoutRedirectUri))
            //{
            //    return RedirectPreserveMethod(logoutContext.PostLogoutRedirectUri);
            //}
            //else
            //{
            //    return RedirectToAction(nameof(HomeController.Index), "Home");
            //}
        }
    }
}